using System;
using System.Collections.Generic;
using System.IO;

namespace WindowsPhoneToolbox.Util
{
    [Serializable]
    public class WpIsolateSaveData
    {
        #region Singleton

        private static WpIsolateSaveData _current;

        public static WpIsolateSaveData Current
        {
            get { return _current ?? (_current = Load()); }
        }

        #endregion


        public  List<WpDeployApplication> WpApplication { get; set; }

        private WpIsolateSaveData()
        {
            WpApplication = new List<WpDeployApplication>();
        }

        internal void AddData(WpDeployApplication data)
        {
            var item = WpApplication.Find(wp => wp.Guid == data.Guid);
            if (item == null)
            {
                WpApplication.Add(data);
            }
            else
            {
                WpApplication.Remove(item);
                WpApplication.Add(data);
            }
            Save();
        }

        private static WpIsolateSaveData Load()
        {
            var filename = Path.Combine(FolderData(), Constants.IsolateFileName);

            var result = new WpIsolateSaveData();
            if (File.Exists((filename)))
            {
                using (var stream = File.Open(filename, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite))
                {
                    var formatter = new System.Xml.Serialization.XmlSerializer(new WpIsolateSaveData().GetType());
                    result = formatter.Deserialize(stream) as WpIsolateSaveData;
                }
            }
            return result;
        }

        internal static void Save()
        {
            var filename = Path.Combine(FolderData(), Constants.IsolateFileName);

            using (var stream = File.Open(filename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite))
            {
                var formatter = new System.Xml.Serialization.XmlSerializer(new WpIsolateSaveData().GetType());
                formatter.Serialize(stream, _current);
            }
        }

        internal static string FolderData()
        {
            var toolFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "WindowsPhoneCommands");
            if (!Directory.Exists(toolFolder))
                Directory.CreateDirectory(toolFolder);
            return toolFolder;
        }

    }
}